package com.lbiuse.cwc.wechat.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lbiuse.cwc.wechat.service.WechatService;
import com.lbiuse.wx.api.WeChatAPI;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


/**
 * 微信核心控制器
 *
 * @author jinglupeng.cc
 */
@Controller
@RequestMapping("/wx/core")
public class WechatController {
    private final static Logger logger = Logger.getLogger(WechatController.class);
    public static String TOKEN = "lbiuse2015";
    public static String APPID = "wx9321081b57b3ab18";
    WeChatAPI api = WeChatAPI.getAPI("");
    private WechatService service;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String get(HttpServletRequest request) {
        try {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            logger.info("signature = " + signature);
            logger.info("timestamp = " + timestamp);
            logger.info("nonce = " + nonce);
            logger.info("echostr = " + echostr);

            if (api.checkSignature(TOKEN, signature, timestamp, nonce)) {
                logger.info("success");
                return echostr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("failed");
        return "failed";
    }
    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        logger.info("core post");
        String result = "";
        try {
            InputStream is = request.getInputStream();
            String message = IOUtils.toString(is);
            is.close();
            logger.info("core invoked");
            logger.info(message);
            result = service.handleMessage(message, APPID);
            if (result == null)
                result = "";
            logger.info("result:" + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.getOutputStream().write(result.getBytes("UTF-8"));
    }

}
